package com.atguigu.flink.chapter05.sink;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Flink05_Sink_Jdbc {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        DataStream<WaterSensor> s1 =
                //            env.socketTextStream("hadoop162", 9999)
                env.fromElements(
                        new WaterSensor("sensor_1", 1L, 10),
                        new WaterSensor("sensor_1", 2L, 20),
                        new WaterSensor("sensor_1", 5L, 20),
                        new WaterSensor("sensor_2", 3L, 30),
                        new WaterSensor("sensor_1", 4L, 40),
                        new WaterSensor("传感器", 4L, 40)
                );

        s1.addSink(JdbcSink.sink(
                "insert into sensor values(?, ?, ?) on duplicate key update vc=?",
                new JdbcStatementBuilder<WaterSensor>() {
                    @Override
                    public void accept(PreparedStatement ps, WaterSensor value) throws SQLException {
                        ps.setString(1, value.getId());
                        ps.setLong(2, value.getTs());
                        ps.setInt(3, value.getVc());
                        ps.setInt(4, value.getVc());
                    }
                },
                new JdbcExecutionOptions.Builder()
                    .withBatchIntervalMs(1000)
                    .withBatchSize(1024)
                    .withMaxRetries(3)
                    .build(),
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                    .withDriverName("com.mysql.jdbc.Driver")
                    .withUrl("jdbc:mysql://hadoop162:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false")
                    .withUsername("root")
                    .withPassword("aaaaaa")
                    .build()

        ));

        env.execute();
    }

}
